﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using DG.Tweening;

public class Rag : CleanDraggableItemBase,IBeginDragHandler,IDragHandler,IEndDragHandler {

    protected override void Start()
    {
        base.Start();

        m_showTrans = WashResController.Instance.ragPoint;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        IsOnDragging = true;
    }

    public void OnDrag(PointerEventData eventData)
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Vector3 planePos = m_Is_EnterHit ? m_last_targetPosition : m_showTrans.position;
        plane = new Plane(m_player.forward, planePos);
        float distance;
        m_isOptStateChanged = false;

        if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Wash")))
        {
            if (hit.transform.name.StartsWith("VB"))
            {
                m_isOptStateChanged = true;
                //m_last_targetPosition = m_showtrans_targetPosition = hit.point + hit.normal * offsetOnNormal;
                if (!IsOutOfDragfield(hit.point))
                {
                    m_Is_EnterHit = true;
                    m_last_targetPosition = m_showtrans_targetPosition = new Vector3(hit.point.x, hit.point.y, 54);
                    m_showtrans_targetRotation = Quaternion.LookRotation(hit.normal * -1);
                    return;
                }
                //else
                //{
                //    m_last_targetPosition = m_showtrans_targetPosition = new Vector3(hit.point.x,hit.point.y,m_showTrans.position.z);
                //}
                //return;
            }
        }

        if (plane.Raycast(ray, out distance))
        {
            Vector3 hitpoint = ray.GetPoint(distance);
            if (!IsOutOfDragfield(hitpoint))
            {
                transform.position = hitpoint;
                transform.rotation = Quaternion.LookRotation(m_player.forward * -1);
            }
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        MoveBack();
    }

    private bool IsOutOfDragfield(Vector3 point)
    {
        bool value = false;
        if (point.y <= m_colliderPlaneRect.y - m_colliderPlaneRect.height)
            value = true;

        return value;
    }

    protected void OnDrawGizmos()
    {
        Gizmos.color = Color.blue;

        if (m_showTrans != null)
        {
            Vector3 centerPos = new Vector3(m_colliderPlaneRect.x + m_colliderPlaneRect.width / 2, m_colliderPlaneRect.y - m_colliderPlaneRect.height / 2, m_player.position.z);
            Gizmos.DrawWireCube(centerPos, new Vector3(m_colliderPlaneRect.width, m_colliderPlaneRect.height, 0.5f));
        }
    }

}
